package com.rainwood.water_authority.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.RecyclerView;

import com.android.zxing.android.QRCodeCaptureActivity;
import com.rainwood.water_authority.R;
import com.rainwood.water_authority.action.StatusAction;
import com.rainwood.water_authority.aop.SingleClick;
import com.rainwood.water_authority.base.MyBaseActivity;
import com.rainwood.water_authority.event.FaLiaoEvent;
import com.rainwood.water_authority.event.ShouLiaoEvent;
import com.rainwood.water_authority.http.request.InStockScanApi;
import com.rainwood.water_authority.http.request.IssueCommitApi;
import com.rainwood.water_authority.http.request.IssueDetailApi;
import com.rainwood.water_authority.http.request.ShouLiaoDetilsUpdateApi;
import com.rainwood.water_authority.http.request.ShouLiaoListApi;
import com.rainwood.water_authority.http.request.ShouLiaosubmitApi;
import com.rainwood.water_authority.http.response.IssueDetailBean;
import com.rainwood.water_authority.http.response.ShouLiaoListBean;
import com.rainwood.water_authority.http.response.ShouLiaoScanBean;
import com.rainwood.water_authority.http.response.SimpleResultBean;
import com.rainwood.water_authority.other.IntentKey;
import com.rainwood.water_authority.ui.adapter.IssueNoticeBaseAdapter;
import com.rainwood.water_authority.ui.adapter.ShouLioListAdapter;
import com.rainwood.water_authority.ui.dialog.MessageDialog;
import com.rainwood.water_authority.util.Constants;
import com.rainwood.water_authority.util.JsonUtils;
import com.rainwood.water_authority.util.ListUtils;
import com.rainwood.water_authority.util.LogUtils;
import com.rainwood.water_authority.util.SharePrenceHelper;
import com.rainwood.water_authority.widget.HintLayout;
import com.sxs.easyhttp.EasyHttp;
import com.sxs.easyhttp.listener.HttpCallback;
import com.sxs.tools.base.BaseAdapter;
import com.sxs.tools.permission.OnPermission;
import com.sxs.tools.permission.Permission;
import com.sxs.tools.permission.XXPermissions;
import com.sxs.tools.titlebar.TitleBar;
import com.sxs.tools.widget.layout.SettingBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author sxs
 * @date :2020/9/28
 * @desc: 发料通知单
 */
public final class FaLiaoListAct extends MyBaseActivity implements BaseAdapter.OnItemClickListener {

    /**
     * @param materialsId 物资id
     */
    public static void start(Context context, String materialsId) {
        Intent intent = new Intent(context, FaLiaoListAct.class);
        intent.putExtra(IntentKey.ID, materialsId);
        context.startActivity(intent);
    }

    public static void start02(Context context, String id, String from) {
        Intent intent = new Intent(context, FaLiaoListAct.class);
        intent.putExtra("historyid", id);
        intent.putExtra("from", from);
        context.startActivity(intent);
    }

    private RecyclerView mMaterialListView;
    private LinearLayout btn_scan_outbound;
    private SettingBar sb_orderNo;
    private SettingBar sb_name;
    private SettingBar sb_date;
    private ShouLioListAdapter mMaterialsAdapter;
    private String direction;
    private String id, from,orderId;
    private TitleBar title;
    private String saomasource;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_faliaolist;
    }

    @Override
    protected void initView() {
        title = findViewById(R.id.title);
        title.setLeftTitle("发料单");
        title.setRightTitle("发料完成");
        mMaterialListView = findViewById(R.id.rv_material_list);
        btn_scan_outbound = findViewById(R.id.btn_scan_outbound);
        Button confirmBtn = findViewById(R.id.btn_confirm);
        sb_orderNo = findViewById(R.id.sb_orderNo);
        sb_name = findViewById(R.id.sb_name);
        sb_date = findViewById(R.id.sb_date);

        mMaterialsAdapter = new ShouLioListAdapter(this,1);
        mMaterialsAdapter.setOnItemClickListener(this);
        mMaterialListView.setAdapter(mMaterialsAdapter);
        btn_scan_outbound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanner();
            }
        });
    }

    private void scanner() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all) {
                            //跳转扫码页面
                            Intent intent = new Intent(FaLiaoListAct.this, QRCodeCaptureActivity.class);
                            intent.putExtra(QRCodeCaptureActivity.STATUS_BAR_COLOR, Color.parseColor("#99000000"));
                            startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (quick) {
                            toast(R.string.common_permission_fail);
                            XXPermissions.startPermissionActivity(getActivity(), false);
                        } else {
                            toast(R.string.common_permission_hint);
                        }
                    }
                });

    }

    //获取扫码结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_SCAN_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String result = null;
            if (bundle != null) {
                result = bundle.getString(QRCodeCaptureActivity.CODE_CONTENT);
                LogUtils.d(TAG, "-------- result-------- " + result);
            }
            if (TextUtils.isEmpty(result)) {
                toast("未识别到任何内容");
                return;
            }
            additem(result);
            //
//            FaLiaoListAct.start(this, result);
        }
    }
    private void additem(String result) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("orderId", orderId);
        hashMap.put("code", result);
        hashMap.put("from", from);
        hashMap.put("num", "1");
        hashMap.put("direction", direction);
        EasyHttp.post(this)
                .api(new ShouLiaoDetilsUpdateApi()
                        .setId(hashMap))
                .request(new HttpCallback<SimpleResultBean>(this) {
                    @Override
                    public void onSucceed(SimpleResultBean result) {
                        toast(result.getWarn());
                        if (result.getCode() == 1) {
                            onfreshdata();
                        }
                    }
                });
    }
    private void onfreshdata(){
        if (getString(IntentKey.ID) != null) {
            String id = getString(IntentKey.ID);
            requestDatum(id);
        } else {
            //来源历史记录
            String history = getString("historyid");
            String from = getString("from");
            EventBus.getDefault().postSticky(new ShouLiaoEvent(history, from));
        }
    }

    private HashMap<String, String> substring(String id) {
        HashMap<String, String> hashMap = new HashMap<>();
        String no = id.substring(3, id.indexOf("&", 0));
        String type = id.substring(id.indexOf("=", 5) + 1, id.indexOf("&direction", 0));
        String direction = id.substring(id.indexOf("&direction=") + 11, id.length());
        hashMap.put("no", no);
        hashMap.put("type", type);
        hashMap.put("direction", direction);
        this.direction = direction;
        return hashMap;
    }

    @Override
    protected void initData() {
        //来源扫码
        if (getString(IntentKey.ID) != null) {
            String id = getString(IntentKey.ID);
            requestDatum(id);
        } else {
            //来源历史记录
            String history = getString("historyid");
            String from = getString("from");
            EventBus.getDefault().postSticky(new FaLiaoEvent(history, from));
        }
    }

    private void requestDatum(String id) {
        HashMap hashMap = substring(id);
        EasyHttp.post(this)
                .api(new InStockScanApi()
                        .setId(hashMap))
                .request(new HttpCallback<ShouLiaoScanBean>(this) {
                    @Override
                    public void onSucceed(ShouLiaoScanBean result) {
                        if (result.getData() != null && result.getData().getInfo() != null) {
                            saomasource=result.getData().getSource();
                            EventBus.getDefault().post(new FaLiaoEvent(result.getData().getInfo().get(0).getId(),
                                    result.getData().getSource()));
                        } else {
                            if (result.getCode() == 0) {
                                toast(result.getWarn());
                                ErrorPageAty.start(getContext(), "入库扫码失败");
                                finish();
                            }
                        }
                    }
                });
    }

    @Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void onGetMessage(FaLiaoEvent message) {
        this.id = message.id;
        saomasource=message.from;
//        this.from = message.from;
        orderId = message.id;
        HashMap hashMap = new HashMap();
        hashMap.put("id", message.id);
        hashMap.put("from", message.from);
        EasyHttp.post(this)
                .api(new ShouLiaoListApi()
                        .setId(hashMap))
                .request(new HttpCallback<ShouLiaoListBean>(this) {
                    @Override
                    public void onSucceed(ShouLiaoListBean result) {
                        if (result.getData() != null && result.getData().getInfo() != null) {
                            from=result.getData().getSource();
                            direction=result.getData().getDirection();
                            sb_orderNo.setRightText(result.getData().getInfo().getOrderNo());
                            sb_name.setRightText(result.getData().getInfo().getName());
                            sb_date.setRightText(result.getData().getInfo().getDate());

                            saveshouliao(result.getData().getInfo(), result.getData().getDirection(), message.getFrom());
                        }

                        if (result.getData() != null && result.getData().getRecord() != null) {
//                            if (ListUtils.getSize(result.getData().getInfo()) == 0) {
//                                TextView headView = mInventoryListView.addHeaderView(R.layout.picker_item);
//                                headView.setText("暂无物资数据");
//                                return;
//                            }
                            mMaterialsAdapter.clearData();
                            mMaterialsAdapter.setData(result.getData().getRecord());
                        }
                    }
                });
    }

    //保存扫描收料之后的数据缓存
    private void saveshouliao(ShouLiaoListBean.DataBean.InfoBean bean, String direction, String source) {
        List<ShouLiaoListBean.DataBean.InfoBean> list = new ArrayList<>();
        String pandianlist = SharePrenceHelper.getStringData("faliao");
        if (pandianlist != null && !pandianlist.equals("")) {
            try {
                list = JsonUtils.jsonToArray(pandianlist, ShouLiaoListBean.DataBean.InfoBean.class);
                boolean ishas = false;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId().equals(bean.getId())) {
                        ishas = true;
                        break;
                    }
                }
                if (ishas == false) {
                    bean.setDirection(direction);
                    bean.setSource(source);
                    list.add(bean);
                    SharePrenceHelper.setInfo("faliao", JsonUtils.arrayToJson(list));

                }
            } catch (Exception e) {

            }
        } else {
            bean.setDirection(direction);
            bean.setSource(source);
            list.add(bean);
            try {
                SharePrenceHelper.setInfo("faliao", JsonUtils.arrayToJson(list));
            } catch (JsonUtils.JsonException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        if (recyclerView.equals(mMaterialListView)) {
            FaLiaoDetilsAct.start(this, mMaterialsAdapter.getItem(position).getId(),
                    direction, from);
        }
    }

    @Override
    public void onRightClick(View v) {
        if (ListUtils.getSize(mMaterialsAdapter.getData()) != 0) {
            new MessageDialog.Builder(this)
                    .setMessage("确定完成本次发料吗？")
                    .setListener(dialog -> commitInventoryDatum()).show();
        } else {
            commitInventoryDatum();
        }
    }

    private void commitInventoryDatum() {
        if (id != null && from != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("id", id);
            hashMap.put("from", saomasource);
            EasyHttp.post(this)
                    .api(new ShouLiaosubmitApi()
                            .setId(hashMap))
                    .request(new HttpCallback<SimpleResultBean>(this) {
                        @Override
                        public void onSucceed(SimpleResultBean result) {
                            toast(result.getWarn());

                            if (result.getCode() == 1) {
                                delte(id);
                                postDelayed(() -> finish(), 100);
                            }
                        }
                    });
        }
    }

    private void delte(String id) {
        List<ShouLiaoListBean.DataBean.InfoBean> list = new ArrayList<>();
        String pandianlist = SharePrenceHelper.getStringData("faliao");
        if (pandianlist != null && !pandianlist.equals("")) {
            try {
                list = JsonUtils.jsonToArray(pandianlist, ShouLiaoListBean.DataBean.InfoBean.class);
                boolean ishas = false;
                int first = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getId().equals(id)) {
                        ishas = true;
                        first = i;
                        break;
                    }
                }
                if (ishas == true) {
                    list.remove(first);
                    SharePrenceHelper.setInfo("faliao", JsonUtils.arrayToJson(list));
                }
            } catch (Exception e) {

            }
        }

    }
}
